package com.ruoyi.framework.web.service;
 
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.AppUser;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginAppUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.common.utils.sign.Md5Utils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.system.service.IAppUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
 
import javax.annotation.Resource;
import java.util.Objects;

import static com.ruoyi.common.utils.SecurityUtils.getLoginAppUser;

/**
 * 登录校验方法
 *
 * @author ruoyi
 */
@Component
public class AppLoginService {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Resource
    private AppTokenService appTokenService;
    @Resource
    private IAppUserService appUserSevice;
 
 
    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @return 结果
     */
    public String login(String username, String password) {
        AppUser appUser = appUserSevice.selectAppUserByUserName(username);
        if (appUser == null) {
            throw new ServiceException("用户不存在");
        }
        if (!appUserSevice.checkPassword(password, appUser.getPassword())) {
            throw new ServiceException("密码不正确");
        }
        LoginAppUser loginAppUser = new LoginAppUser(appUser.getUserId(), appUser);
        recordLoginInfo(loginAppUser.getUserId());
        // 生成token
        return appTokenService.createAppToken(loginAppUser);
    }
 
    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    private void recordLoginInfo(Long userId) {
        AppUser appUser = new AppUser();
        appUser.setUserId(userId);
        appUser.setLoginIp(IpUtils.getIpAddr());
        appUser.setLoginDate(DateUtils.getNowDate());
        appUserSevice.updateAppUser(appUser);
    }

    public void register(AppUser user) {
        String msg = "", username = user.getUserName(), password = user.getPassword();

        if (StringUtils.isEmpty(username))
        {
            msg = "用户名不能为空";
        }
        else if (StringUtils.isEmpty(password))
        {
            msg = "用户密码不能为空";
        }
        else if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            msg = "账户长度必须在2到20个字符之间";
        }
        else if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            msg = "密码长度必须在5到20个字符之间";
        }
        else if (Objects.nonNull(appUserSevice.selectAppUserByUserName(user.getUserName())))
        {
            msg = "保存用户'" + username + "'失败，注册账号已存在";
        }
        else if (!appUserSevice.checkPhoneUnique(user)) {
            msg = "注册失败,手机号已存在";
        } else if (!appUserSevice.checkEmailUnique(user)) {
            msg = "注册失败,邮箱已存在";
        } else
        {
            user.setPassword(Md5Utils.hash(user.getPassword()));
            int regFlag = appUserSevice.insertAppUser(user);
            if (regFlag == 0)
            {
                msg = "注册失败,请联系系统管理人员";
            }
        }
        if (StringUtils.isNotEmpty(msg)) {
            throw new ServiceException(msg);
        }
    }

    public void updateProfile(AppUser user) {
        if (StringUtils.isNotEmpty(user.getMobile()) && !appUserSevice.checkPhoneUnique(user))
        {
            throw new ServiceException("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail()) && !appUserSevice.checkEmailUnique(user))
        {
            throw new ServiceException("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        else
        {
            int row = appUserSevice.updateAppUser(user);
            if (row == 0) {
                throw new ServiceException("修改个人信息异常，请联系管理员");
            }
        }
    }

    public boolean checkPassword(String oldPassword, String password) {
        return appUserSevice.checkPassword(oldPassword,password);
    }

    public void updatePwd(String newPassword) {
        AppUser user = getLoginAppUser().getAppUser();
        user.setPassword(Md5Utils.hash(newPassword));
        int row = appUserSevice.updateAppUser(user);
        if (row > 0) {
            appTokenService.refreshToken(getLoginAppUser());
        }
    }

    public boolean updateUserAvatar(String avatar) {
        AppUser user = getLoginAppUser().getAppUser();
        user.setAvatar(avatar);
        return appUserSevice.updateAppUser(user) > 0;
    }
}